<?php

namespace Siese\EntityBundle\Form\EventListener;
 
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Doctrine\ORM\EntityRepository;
 
class AddEstadosFieldSubscriber implements EventSubscriberInterface
{
    private $propertyPathToMunicipio;
    
 
    public function __construct($propertyPathToMunicipio)
    {
        $this->propertyPathToMunicipio = $propertyPathToMunicipio;
      
    }
 
    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SET_DATA => 'preSetData',
            FormEvents::PRE_SUBMIT   => 'preSubmit'
        );
    }
 
    private function addEstadoForm($form, $estado = null)
    {
        $arregloIdSedes=array(1);
        
        $formOptions = array(
            'class'         => 'SieseEntityBundle:CatEstados',
            'mapped'        => false,
            'label'         => 'Estado',
            'empty_value'   => 'Seleccione una Opción',
            'attr'          => array(
                'class' => 'estado_selector form-control',
            ),
        );
        
        $admin=false;
        if($admin == false ):
        $formOptions['query_builder'] =  
                function(EntityRepository $er) use ($arregloIdSedes)
                {
                                                      return $er->createQueryBuilder('u')
                                                                     ->join('u.sede','s')
                                                                     ->where('s.id IN(:arregloIds)')
                                                                    ->setParameter('arregloIds',array_values($arregloIdSedes));
             };
        endif;
        
        if ($estado) {
            $formOptions['data'] = $estado;
        }
 
        $form->add('estadoEnt', 'entity', $formOptions);
    }
 
    public function preSetData(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();
 
        if (null === $data) {
            return;
        }
 
        $accessor = PropertyAccess::getPropertyAccessor();
 
        $entidad    = $accessor->getValue($data, $this->propertyPathToMunicipio);
        $estado = ($entidad) ? $entidad->getEstado() : null;

        $this->addEstadoForm($form, $estado);
    }
 
    public function preSubmit(FormEvent $event)
    {
        $form = $event->getForm();
 
        $this->addEstadoForm($form);
    }
}